package cn.com.thinvent.dispatch.web.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    private static final String UPLOAD_DIR = "D://static//";

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "上传文件为空";
            }

            // 确保上传目录存在
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            String fileName = file.getOriginalFilename();
            Path filePath = uploadPath.resolve(fileName);
            file.transferTo(filePath.toFile());

//            String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
//                    .path("/" + UPLOAD_DIR)
//                    .path(fileName)
//                    .toUriString();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传文件失败";
        }
    }

    @GetMapping("/images/{filePath}")
    public ResponseEntity<byte[]> getImage(@PathVariable("filePath") String filePath) {
        Path imagePath = Paths.get(UPLOAD_DIR, filePath);
        FileSystemResource fileSystemResource = new FileSystemResource(imagePath);

        if (!fileSystemResource.exists()) {
            return ResponseEntity.notFound().build();
        }

        try {
            byte[] bytes = Files.readAllBytes(imagePath);
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG) // 根据实际情况更改 MIME 类型
                    .body(bytes);
        } catch (IOException e) {
            return ResponseEntity.ok().build();
        }
    }
}